package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.MsgPhraseBean;
import com.koron.css2.baseConfig.mapper.MsgPhraseMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.koron.util.ValidationKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 短信模板-保存
 *
 * @author 廖大富
 */
public class MsgPhraseSave implements ServerInterface {

    private static Logger logger = LogManager.getLogger(MsgPhraseSave.class);

    @Override
    @ValidationKey(clazz = MsgPhraseBean.class,method = "insert")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            MsgPhraseMapper mapper = factory.getMapper(MsgPhraseMapper.class);
            //获取短信模板信息
            List<MsgPhraseBean> beans = JsonUtils.jsonToList(JsonUtils.objectToJson(req.getData()), MsgPhraseBean.class);
            if (null == beans || beans.size() == 0) {
                return MessageBean.create(Constant.NOT_NULL, "参数为空", void.class);
            }
            for (MsgPhraseBean bean : beans) {
                bean.setCreateInfo(userInfo);
                bean.setStatus(1);
            }
            //先清空历史记录
            mapper.deleteAllMsgPhrase();
            // 再添加新纪录
            mapper.insertMsgPhraseList(beans);
        } catch (Exception e) {
            factory.close(false);
            logger.error("短信模板保存失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "短信模板保存失败", void.class);
        }
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
    }
}